﻿<?php
namespace YDCMS\models;

use PDO;

class BaseModel
{
    /**
     * @var PDO 数据库连接
     */
    protected $db;

    /**
     * @var string 表名
     */
    protected $table;

    /**
     * @var string 主键
     */
    protected $primaryKey = 'id';

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->connect();
    }

    /**
     * 连接数据库
     */
    protected function connect()
    {
        $dsn = sprintf(
            '%s:host=%s;port=%s;dbname=%s;charset=utf8mb4',
            $_ENV['DB_CONNECTION'],
            $_ENV['DB_HOST'],
            $_ENV['DB_PORT'],
            $_ENV['DB_DATABASE']
        );

        $this->db = new PDO($dsn, $_ENV['DB_USERNAME'], $_ENV['DB_PASSWORD'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
    }

    /**
     * 查找单条记录
     * @param mixed $id 主键值
     * @return array|false
     */
    public function find($id)
    {
        $sql = 'SELECT * FROM ' . $this->table . ' WHERE ' . $this->primaryKey . ' = ?';
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$id]);
        return $stmt->fetch();
    }

    /**
     * 查找所有记录
     * @return array
     */
    public function all()
    {
        $sql = 'SELECT * FROM ' . $this->table;
        $stmt = $this->db->query($sql);
        return $stmt->fetchAll();
    }

    /**
     * 创建记录
     * @param array $data 数据
     * @return int 插入ID
     */
    public function create($data)
    {
        $fields = array_keys($data);
        $values = array_values($data);
        $placeholders = str_repeat('?,', count($fields) - 1) . '?';
        
        $sql = sprintf(
            'INSERT INTO %s (%s) VALUES (%s)',
            $this->table,
            implode(',', $fields),
            $placeholders
        );
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($values);
        
        return $this->db->lastInsertId();
    }

    /**
     * 更新记录
     * @param mixed $id 主键值
     * @param array $data 数据
     * @return bool
     */
    public function update($id, $data)
    {
        $fields = array_keys($data);
        $values = array_values($data);
        $set = implode('=?,', $fields) . '=?';
        
        $sql = sprintf(
            'UPDATE %s SET %s WHERE %s = ?',
            $this->table,
            $set,
            $this->primaryKey
        );
        
        $values[] = $id;
        
        $stmt = $this->db->prepare($sql);
        return $stmt->execute($values);
    }

    /**
     * 删除记录
     * @param mixed $id 主键值
     * @return bool
     */
    public function delete($id)
    {
        $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $this->primaryKey . ' = ?';
        $stmt = $this->db->prepare($sql);
        return $stmt->execute([$id]);
    }
}
